/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tnviet.proj.jna.dialog;

import com.jgoodies.forms.factories.ButtonBarFactory;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import org.jdesktop.swingx.JXTitledPanel;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.api.renderers.SubstanceDefaultTableCellRenderer;
import tnviet.proj.jna.JNMainFrame;
import tnviet.proj.jna.JNPacketAnalyzerLoader;
import tnviet.proj.jna.Program;
import tnviet.proj.jna.analyzer.JNPacketAnalyzer;
import tnviet.proj.jna.table.ProtocolColor;
import tnviet.proj.jna.utilities.ResourceManager;

/**
 *
 * @author Administrator
 */
public class ColorRulesDialog extends JDialog {

    ResourceManager resourceManager = new ResourceManager(Program.class, Program.locale);
    String INSSERT_CMD = "INSERT INTO JNA_COLOR (PROTOCOL, RED, GREEN, BLUE) VALUES(?,?,?,?)";
    String UPDATE_CMD = "UPDATE JNA_COLOR SET RED = ?, GREEN = ?, BLUE = ? WHERE PROTOCOL = ?";
    String SELECT_CMD = "SELECT * FROM JNA_COLOR WHERE PROTOCOL = ?";
    JNPacketAnalyzer[] analyzers = JNPacketAnalyzerLoader.getAnalyzers();
    Connection con = Program.connection;
    Vector data = new Vector();
    JButton okButton, cancelButton;
    JNMainFrame frame;

    public ColorRulesDialog(Frame owner) {
        super(owner);
        frame = (JNMainFrame)owner;
        this.setTitle(resourceManager.getString("colorRules.text"));
        this.setModal(true);
        this.InsertIfNotExist();
        ColorRulesModel model = new ColorRulesModel();
        JTable table = new JTable(model);
        table.getColumnModel().getColumn(1).setCellEditor(new ColorEditor());
        table.getColumnModel().getColumn(1).setCellRenderer(new CorlorRenderer());
        okButton = new JButton(resourceManager.getString("okButton.text"));
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for(int i = 0; i<data.size(); i++){
                    ProtocolColor pC = (ProtocolColor)data.elementAt(i);
                    UpdateColor(pC.getProtocol(), pC.getColor());
                    setVisible(false);
                    frame.updateColorRules();
                    dispose();
                }
            }
        });
        cancelButton = new JButton(resourceManager.getString("cancelButton.text"));
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                dispose();
            }
        });
        JPanel okCancelBar = ButtonBarFactory.buildOKCancelBar(okButton, cancelButton);
        JScrollPane scroll = new JScrollPane(table);
        JXTitledPanel titlePane = new JXTitledPanel(resourceManager.getString("colorRules.text"),scroll);
        this.add(titlePane, BorderLayout.CENTER);
        this.add(okCancelBar, BorderLayout.PAGE_END);
        this.pack();
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(owner);
    }

    protected void UpdateColor(String protocol, Color color){
        PreparedStatement stm;
        try {
            stm = con.prepareStatement(UPDATE_CMD);
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            stm.setInt(1, red);
            stm.setInt(2, green);
            stm.setInt(3, blue);
            stm.setString(4, protocol);
            stm.executeUpdate();

        } catch (SQLException e) {
        }
    }

    protected void InsertIfNotExist(){
        PreparedStatement selectStm;
        Color color = (Color) UIManager.get("Label.background");
        PreparedStatement stm;
        try {
            selectStm = con.prepareStatement(SELECT_CMD);
            stm = con.prepareStatement(INSSERT_CMD);
            for(int i=0; i<analyzers.length;i++){
                ProtocolColor pC = null;
                String protocol = analyzers[i].getProtocolName();
                selectStm.setString(1, protocol);
                ResultSet rs = selectStm.executeQuery();
                if(rs.next()){
                    int red = rs.getInt(3);
                    int green = rs.getInt(4);
                    int blue = rs.getInt(5);
                    Color tempColor = new Color(red, green, blue);
                    pC = new ProtocolColor(protocol, tempColor);
                } else {
                    stm.setString(1, protocol);
                    stm.setInt(2,color.getRed());
                    stm.setInt(3,color.getGreen());
                    stm.setInt(4,color.getBlue());
                    stm.executeUpdate();
                    pC = new ProtocolColor(protocol, color);
                }
                data.addElement(pC);
            }
        } catch (SQLException ex) {
        }
    }

    public static void main(String[] args){
        Color color = UIManager.getColor("Button.background");
        System.out.println(color.toString());
    }

    class ColorRulesModel extends AbstractTableModel{

        public int getRowCount() {
            return data.size();
        }

        public int getColumnCount() {
            return 2;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            ProtocolColor pC = (ProtocolColor) data.elementAt(rowIndex);
            if(columnIndex == 0) return pC.getProtocol();
            else return pC.getColor();

        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            if (columnIndex == 0) return false;
            else return true;
        }

        @Override
        public String getColumnName(int column) {
            if(column == 0) return resourceManager.getString("protocolName");
            else return resourceManager.getString("color");
        }

        public void setValueAt(Object value, int row, int col) {
            ProtocolColor pC = (ProtocolColor) data.elementAt(row);
            pC.setColor(((Color)value));
            fireTableCellUpdated(row, col);

        }


    }

    class ColorEditor extends AbstractCellEditor implements TableCellEditor, ActionListener{

        Color currentColor;
        JButton button;
        JColorChooser colorChooser;
        JDialog dialog;
        protected static final String EDIT = "edit";



        public ColorEditor() {
            button = new JButton();
            button.setActionCommand(EDIT);
            button.addActionListener(this);
            button.setBorderPainted(true);

            colorChooser = new JColorChooser();
            dialog = JColorChooser.createDialog(button,
                                            resourceManager.getString("pickColor"),
                                            true,  //modal
                                            colorChooser,
                                            this,  //OK button handler
                                            null); //no CANCEL button handler
        }

        public Object getCellEditorValue() {
            return currentColor;
        }

        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            currentColor = (Color)value;
            return button;
        }

        public void actionPerformed(ActionEvent e) {
            if (EDIT.equals(e.getActionCommand())) {
            //The user has clicked the cell, so
            //bring up the dialog.
            button.setBackground(currentColor);
            colorChooser.setColor(currentColor);
            dialog.setVisible(true);

            //Make the renderer reappear.
            fireEditingStopped();

            } else { //User pressed dialog's "OK" button.
                currentColor = colorChooser.getColor();

            }

        }

    }


    class CorlorRenderer extends JLabel implements TableCellRenderer{

        Border unselectedBorder = null;
        Border selectedBorder = null;
        boolean isBordered = true;
        SubstanceDefaultTableCellRenderer defaultRenderer = new SubstanceDefaultTableCellRenderer();
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component comp = defaultRenderer.getTableCellRendererComponent(table, "    ", isSelected, hasFocus, row, column);
            if(comp instanceof JLabel){
                ((JLabel)comp).setOpaque(true);
                ((JLabel)comp).setBackground((Color)value);
            }
            if (isBordered) {
            if (isSelected) {
                if (selectedBorder == null) {
                    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                              table.getSelectionBackground());
                }
                setBorder(selectedBorder);
            } else {
                if (unselectedBorder == null) {
                    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
                                              table.getBackground());
                }
                ((JLabel)comp).setBorder(unselectedBorder);
            }
        }

            return comp;
        }

    }

}
